const RuleFactory = require('./RuleFactory');

/**
 * 使用map做本地缓存，并加入负载均衡规则
 */
class LoadBalancer {

    cache = null; //本地Map缓存
    rule = null; //负载均衡规则

    constructor(strategy) {
        this.cache = new Map();

        this.rule = RuleFactory.getRule(strategy);
    }

    /**
     * 更新缓存
     * @param {String} path 服务路径
     * @param {Array<String>} nodes 真实访问集合
     */
    updateCache(path, nodes) {
        console.info(`LoadBalancer update cache service : ${path}, nodes : ${JSON.stringify(nodes)}`);

        this.cache.set(path, nodes);
    }

    /**
     * 从缓存中获取访问地址
     * 
     * @param {String} path 服务路径
     * @returns String 真实访问地址
     */
    getRealPath(path) {
        let nodes = this.cache.get(path);

        if (!nodes)
            throw new Error(`service:${path} instance not found`);

        if (nodes.length == 1)
            return nodes[0];

        //若存在多个服务地址，使用负载均衡规则进行获取
        return this.rule.choose(path, nodes);
    }
}

module.exports = LoadBalancer;